package bb.lanxing.util.image;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import bb.lanxing.R;
import bb.lanxing.common.config.GlideApp;

public class GlideUtil {
    private static GlideUtil glideUtil;

    private GlideUtil() {
    }

    public static GlideUtil getInstance() {
        if (glideUtil == null) {
            synchronized (GlideUtil.class) {
                if (glideUtil == null) {
                    glideUtil = new GlideUtil();
                }
            }
        }
        return glideUtil;
    }

    public void showImage(String url, ImageView imageView) {
        RequestBuilder requestBuilder = getRequestBuilder(url, imageView.getContext());
        if (requestBuilder != null) {
            requestBuilder.into(imageView);
        }
    }

    public void showImage(String url, final TextView imageView, int placeholder) {
        RequestBuilder requestBuilder = getRequestBuilder(url, placeholder, imageView.getContext());
        if (requestBuilder != null) {
            requestBuilder.into(new SimpleTarget<Drawable>() {

                @Override
                public void onResourceReady(Drawable resource, Transition transition) {
                    imageView.setBackground(resource);
                }

                @Override
                public void onLoadCleared(Drawable placeholder2) {
                    imageView.setBackground(placeholder2);
                }
            });
        }
    }

    private RequestBuilder<Drawable> getRequestBuilder(String url, Context context) {
        return getRequestBuilder(url, R.drawable.ic_default, context);
    }

    private RequestBuilder<Drawable> getRequestBuilder(String url, int placeholder, Context context) {
        if (isValidContextForGlide(context)) {
            return GlideApp.with(context).load(url).placeholder(placeholder).error(placeholder).fallback(placeholder).diskCacheStrategy(DiskCacheStrategy.ALL);
        }
        return null;
    }

    public static boolean isValidContextForGlide(final Context context) {
        if (context == null) {
            return false;
        }
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            return (!activity.isDestroyed()) && !activity.isFinishing();
        }
        return true;
    }
}